package com.jacen.fzxs.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ClassUtil {

	/**
	 * 设置对象的值
	 * 
	 * @param object
	 * @param att
	 * @param value
	 * @param type
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static void setValue(Object object, String att, Object value, Class<?> type) throws SecurityException,
			NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		att = Character.toUpperCase(att.charAt(0)) + att.substring(1);
		Method method = object.getClass().getMethod("set" + att, type);
		method.invoke(object, value);
	}

	/**
	 * 获取实体类的属性值
	 * 
	 * @param object
	 * @param property
	 * @return
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static Object getValue(Object object, String property) throws SecurityException, NoSuchMethodException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		String methodName = "get" + Character.toUpperCase(property.charAt(0)) + property.substring(1);
		Method method = object.getClass().getMethod(methodName);
		Object object2 = method.invoke(object);
		return object2;
	}

	/**
	 * 将属性名格式为java实体的属性名
	 * 
	 * @param property
	 * @return
	 */
	public static String changeToEntitiesPropertyName(String property) {
		StringBuilder name = new StringBuilder();
		String[] segs = property.split("[_]");
		if (segs.length < 2) {
			return property;
		}
		name.append(segs[0]);
		for (int i = 1; i < segs.length; i++) {
			name.append(StrUtils.toFirstUpperCase(segs[i]));
		}
		return name.toString();
	}

	/**
	 * 将java实体属性名转换成数据库显示格式
	 * 
	 * @param str
	 * @return
	 */
	public static String changeToFieldName(String str) {
		char[] chars = str.toCharArray();
		StringBuilder sb = new StringBuilder();
		for (char c : chars) {
			if (Character.isLowerCase(c)) {
				sb.append(c);
			} else {
				sb.append("_");
				sb.append(Character.toLowerCase(c));
			}
		}
		return sb.toString();
	}

}
